package com.huawei.push.controller.service;

import com.huawei.push.controller.Json.ResultJson;
import com.meizu.push.sdk.constant.PushType;
import com.meizu.push.sdk.server.IFlymePush;
import com.meizu.push.sdk.server.constant.PushResponseCode;
import com.meizu.push.sdk.server.constant.ResultPack;
import com.meizu.push.sdk.server.model.push.PushResult;
import com.meizu.push.sdk.server.model.push.VarnishedMessage;
import com.meizu.push.sdk.server.model.statistics.DailyPushStatics;
import com.meizu.push.sdk.utils.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 魅族信息推送
 */
@Component
public class MeiZuAppSendMsg {
    private static Log log = LogFactory.getLog(MeiZuAppSendMsg.class);

    /**
     * 魅族的apid
     */
    @Value("${meiZu.appId}")
    private long appId;
    /**
     * 魅族的Secret
     */
    @Value("${meiZu.appSecret}")
    private String appSecret;

    /**
     * 魅族的key
     */
    @Value("${meiZu.key}")
    private long key;

    /**
     * 发送消息
     * @param title 消息标题
     * @param content 消息内容
     * @param pushIds 是否空判断是否全发
     * @return
     */
    public String sendMsg(String title,String content,List<String> pushIds){
        final int pushSize=1000;
        if (!StringUtils.hasLength(content)){
            return ResultJson.bad("不能发送空消息",null);
        }

        if (CollectionUtils.isEmpty(pushIds)||pushIds.size()==0){
           return sendAll(title,content);
        }
        if (pushIds.size()>pushSize){
            return ResultJson.bad("单次发送用户最大1000个数量，已超出",null);
        }
        try {
          return   sendMany(title,content,pushIds);
        } catch (IOException e) {
            return ResultJson.bad("服务异常",null);
        }
    }

    /**
     * 发给所有人
     * @param title
     * @param content
     * @return
     */
    private String sendAll(String title, String content) {
        //推送对象
        IFlymePush push = new IFlymePush(appSecret);
        //通知栏全部消息推送
        VarnishedMessage message = new VarnishedMessage.Builder().appId(appId)
                .title(title).content(content)
                .noticeExpandType(1)
                .noticeExpandContent(content)
                .clickType(0)
//                .parameters(JSON.parseObject(" {\"k1\":\"value1\",\"k2\":0,\"k3\":\"value3\"}"))
                .offLine(true).validTime(12)
                .suspend(true).clearNoticeBar(true).vibrate(false).lights(false).sound(true)
                .fixSpeed(true).fixSpeedRate(30)
                .pushTimeType(1)
                .startTime(new Date())
                .build();
        ResultPack<Long> result = null;
        try {
            result = push.pushToApp(PushType.STATUSBAR, message);
            if (result.isSucceed()) {
                return ResultJson.ok(result.comment(), null);
            }
            return ResultJson.bad(result.comment(), null);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultJson.bad("通知魅族发送信息异常", null);
        }

    }


    /**
     *
     * @param title 消息标题
     * @param content 内容
     * @param pushIds 目标用户 一次不可超过1000个
     * @throws IOException
     */
    private String sendMany(String title,String content,List<String> pushIds) throws IOException {
        //推送对象
        IFlymePush push = new IFlymePush(appSecret);

        //组装消息
        VarnishedMessage message = new VarnishedMessage.Builder().appId(appId)
                .title(title).content(content)
                .noticeExpandType(1)
                .noticeExpandContent(content)
                .clickType(0)
//                .parameters(JSON.parseObject(" {\"k1\":\"value1\",\"k2\":0,\"k3\":\"value3\"}"))
                .offLine(true).validTime(12)
                .suspend(true).clearNoticeBar(true).vibrate(true).lights(true).sound(true)
                .build();


        // 1 调用推送服务
        ResultPack<PushResult> result = push.pushMessage(message, pushIds);
        if (result.isSucceed()) {
            // 2 调用推送服务成功 （其中map为设备的具体推送结果，一般业务针对超速的 code类型做处理）
            PushResult pushResult = result.value();
            String msgId = pushResult.getMsgId();//推送消息ID，用于推送流程明细排

            Map<String, List<String>> targetResultMap =
                    pushResult.getRespTarget();//推送结果，全部推送成功，则map为empty
            log.info("push msgId:" + msgId);
            log.info("push targetResultMap:" + targetResultMap);
            if (targetResultMap != null && !targetResultMap.isEmpty()) {
                // 3 判断是否有获取超速的target
                if(targetResultMap.containsKey(PushResponseCode.RSP_SPEED_LIMIT.getValue())) {
                    // 4 获取超速的target
                    List<String> rateLimitTarget = targetResultMap.get(PushResponseCode.RSP_SPEED_LIMIT.getValue());
                    log.info("rateLimitTarget is :" + rateLimitTarget);
                    //  业务处理，重推...... 暂时直接返回
                    return ResultJson.bad(result.comment(),rateLimitTarget);
//                    ResultPack<PushResult> result = push.pushMessage(message, pushIds,2);

                }
            }
            return ResultJson.ok(result.comment(),null);
        }
        // 调用推送接口服务异常 eg: appId、appKey非法、推送消息非法.....
        // result.code(); //服务异常码
        // result.comment();//服务异常描述
        //全部超速
           /* if (String.valueOf(ErrorCode.APP_REQUEST_EXCEED_LIMIT.getValue()).equals(result.code())) {
                //TODO 5 业务处理，重推......
                return ResultJson.bad(result.comment(),result.code());
            }*/
        log.info(String.format("pushMessage error code:%s comment:%s", result.code(), result.comment()));
        return ResultJson.bad(result.comment(),result.code());


    }


   

}
